package cc.iteachyou.template.taglib.directives;

import cc.iteachyou.template.dom.VirtualDOMAttr;
import cc.iteachyou.template.dom.VirtualDOMNode;
import cc.iteachyou.template.taglib.IDirectiveHandler;
import cc.iteachyou.template.taglib.result.DirectiveResult;
import cc.iteachyou.template.utils.VariableHelper;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

@Slf4j
public class ElseDirectiveHandler implements IDirectiveHandler {
    @Override
    public Optional<DirectiveResult> handler(VirtualDOMNode.RendererVirtualDOMAttrContext ctx, Map<String, Object> data) {
        VirtualDOMAttr attr = ctx.getAttr();

        VariableHelper variableHelper = VariableHelper.getInstance();
        Map<String, Object> templateData = variableHelper.get();

        if(!templateData.containsKey("dreamer_template_engine_if_result")){
            log.error("Else directive must be after if or else if.");
            throw new RuntimeException("Else directive must be after if or else if.");
        }
        // 获取上下文中的数据，主要是if或else if的返回值
        Boolean flag = (Boolean) templateData.get("dreamer_template_engine_if_result");

        DirectiveResult result = DirectiveResult.builder()
                .name(attr.getName())
                .value(!flag)
                .build();

        // 清空条件判断数据
        templateData.remove("dreamer_template_engine_if_result");

        return Optional.of(result);
    }
}
